import json
import re

from django import http
from django.contrib.auth import login, logout
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import HttpResponse,JsonResponse
from django_redis import get_redis_connection
from apps.user.models import User, Address

#用户名去重
from zmeiduo.settings.dev import logger
from zmeiduo.utils.libs.views import LoginRequiredJSONMixin
from zmeiduo.utils.secret import SecretOauth
from zmeiduo.utils.utils import generate_verify_email_url


class UsernameCountView(View):
    def get(self,request,username):
        try:
            count=User.objects.filter(username=username).count()
        except Exception as a:
            return JsonResponse({'code':400, 'errmsg':'访问数据库失败'})
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})
#手机号去重
class MobileCountView(View):
    def get(self,request,mobile):

        try:
            count=User.objects.filter(mobile=mobile).count()
        except Exception as  e:
            return JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})
#zhuce
class zhuciView(View):
    def post(self,request):
        #接受参数
        dict_dson=json.loads(request.body)
        #解析参数
        username=dict_dson.get("username")
        password = dict_dson.get('password')
        password2 = dict_dson.get('password2')
        mobile = dict_dson.get('mobile')
        allow = dict_dson.get('allow')
        sms_code = dict_dson.get('sms_code')
        # 验证手机号
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        #验证用户名
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})

        #验证密码
        if password !=password2:
            return JsonResponse({"code":400,"ermsg":"密码不一致"})
        if allow !=True:
            return JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})
        # 验证手机验证码是否正确
        # 校验验证码
        # 取出图形验证码
        #链接数据库
        redis_conn=get_redis_connection('verify_code')
        aa=type(redis_conn)
        print(aa)
        redsi_severs=redis_conn.get(mobile)

        #取出来的手机号
        if redsi_severs is None:
            return JsonResponse({'code': 400, 'errmsg': '手机啊为空!'})
        if sms_code !=redsi_severs.decode():
            return JsonResponse({'code': 400, 'errmsg': '不相等为空!'})


        #保存数据库
        try:
            user=User.objects.create_user(mobile=mobile,username=username,password=password)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '注册失败!'})
        #保持登录状态
        login(request,user)
        return JsonResponse({'code': 0, 'errmsg': '注册成功!'})

#登录接口
class LoginView(View):
    def post(self,request):
        dict_abc=json.loads(request.body.decode())
        #接受参数
        username=dict_abc.get('username')
        password=dict_abc.get('password')
        remembered = dict_abc.get('remembered') #是否记住登录
        #校验参数  不能是空的
        if not all([username,password]):
            return JsonResponse({"code": '空的'})
        # #用户名或者手机号登录 判断他是否满足手机号的路由如果不满足 那接受用户名
        # if re.match(r'^1[3-9]\d{9}',username):
        #     usernamem=username
        # else:
        #     usernamem=username

        # if re.match(r'^1[3-9]\d{9}$', username):
        #     # 用户输入的账号是手机号:将USERNAME_FIELD指定为'mobile'字段
        #     User.USERNAME_FIELD = 'mobile'
        # else:
        #     # 用户输入的账号是用户名:将USERNAME_FIELD指定为'username'字段
        #     User.USERNAME_FIELD = 'username'
        #


        try:
            from django.contrib.auth import login, authenticate
            #用django的因为加密的时候是他django加密的  所以也要用django的

            user=authenticate(request,username=username,password=password)

            if user is None:
                return JsonResponse({"code": '没有这个人'})

            #保存登录状态
            login(request,user)

            if remembered != True:
                request.session.set_expiry(0)
            else: #俩周默认的
                # request.session.set_expory(None)
                request.session.set_expiry(None)
        except Exception as e:
            print(e)
            return JsonResponse({"code": e})
        aaa= JsonResponse({"code":0,"成功":'ok'})
        aaa.set_cookie('username',user.username,max_age=3600000)
        return aaa
#退出接口
class LogoutView(View):
    def delete(self, request):
        """实现退出登录逻辑"""
        #清楚session
        logout(request)
        #创建response对象
        response=JsonResponse({"code":0,"errmsg":'ok'})
        #调用对象的delete_cookie 方法 清除cookie
        response.delete_cookie('username')
        return response
    pass
#用户中心
class UserInfoView(LoginRequiredJSONMixin,View):
    def get(self, request):
        """提供个人信息界面"""

        # 获取界面需要的数据,进行拼接
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }

        # 返回响应
        return JsonResponse({'code':0, 'errmsg':'ok','info_data':info_data})
#""添加邮箱"""
class EmailView(View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        #校验参数
        if not email:
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数email有误'})
        #保存
        try:
            request.user.email=email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400,
                                      'errmsg': '添加邮箱失败'})
        # 从 celery_tasks 中导入:
        from celery_tasks.email.tasks import send_verify_email
        # 调用发送的函数:
        verify_url = generate_verify_email_url(request)
        # 发送验证链接:
        send_verify_email.delay(email, verify_url)
        # 响应添加邮箱结果
        return JsonResponse({'code': 0,
                                  'errmsg': 'ok'})
#校验邮箱链接token
class VerifyEmailView(View):
    def put(self,request):
        #接受token
        token=request.get('token')
        #校验
        if not token:
            return JsonResponse({"code":400,"emmsenf":"空"})
        #解密
            # - 2.解密
        data_dict = SecretOauth().loads(token)

        try:
            user = User.objects.get(pk=data_dict.get('user_id'), email=data_dict.get('email'))
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '参数有误!'})
        #修改激活状态
        try:
            user.email_active=True
            user.save()
        except Exception as e:
            return JsonResponse({'code':0 ,'ems':'激活失败'})

        return JsonResponse({'code': 0, 'ems': '激活成功!'})
#新增地址
class CreateAddressView(LoginRequiredJSONMixin,View):
    """新增地址"""
    def post(self, request):
        #判断他是否小于20个
        #先自己查询
        # 1.查询 当前用户的 地址个数
        count = Address.objects.filter(user=request.user).count()

        if count > 20:
            return JsonResponse({'code': 400, 'errmsg': '最多20个地址!'})

        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        #校验参数
    #接受参数
    # 新增
        try:
            address=Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
                )
            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address=address
                request.user.save()
        #新增失败
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '新增地址失败'})
        address_dict = [{
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,

            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,

            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }]

        # 响应保存结果
        return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address': address_dict})
#用户收货地址
class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        #获取所以地址
        addresses=Address.objects.filter(user=request.user,is_deleted=False)
        #整理类型
        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,

                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,

                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_dict_list.append(address_dict)
        #第一层 字典  k v 第二层 字典k v 列表 列表里面还是 kv
        #
        # 获取默认地址id
        default_id = request.user.default_address_id

        #返回
        return http.JsonResponse(
            {'code': 0, 'errmsg': 'ok', 'addresses': address_dict_list, 'default_address_id': default_id})


